<template>
  <div class="wrapper">
    <div class="header">
      <span class="back-btn" @click="goBack">&#8592;</span>
      <h1>商家管理</h1>
      <p>欢迎, {{ user.username }}</p>
    </div>

    <!-- 店铺信息管理 -->
    <div class="section">
      <h2>店铺信息</h2>
      <div class="business-info">
        <div class="info-item">
          <label>店铺名称:</label>
          <input v-model="business.businessName" :disabled="!editingBusiness" />
        </div>
        <div class="info-item">
          <label>店铺地址:</label>
          <input v-model="business.businessAddress" :disabled="!editingBusiness" />
        </div>
        <div class="info-item">
          <label>店铺图片URL:</label>
          <input v-model="business.businessImg" :disabled="!editingBusiness" placeholder="请输入店铺图片网络地址" />
        </div>
        <div class="info-item">
          <label>商铺简介:</label>
          <textarea v-model="business.businessExplain" :disabled="!editingBusiness"></textarea>
        </div>
        <div class="info-item">
          <label>起送价格:</label>
          <input v-model="business.startPrice" type="number" step="0.01" :disabled="!editingBusiness" />
        </div>
        <div class="info-item">
          <label>配送费:</label>
          <input v-model="business.deliveryPrice" type="number" step="0.01" :disabled="!editingBusiness" />
        </div>
        <div class="info-item">
          <label>商铺分类:</label>
          <template v-if="editingBusiness">
            <select v-model="business.orderTypeId">
              <option v-for="t in foodTypeList" :key="t.id" :value="t.id">{{ t.label }}</option>
            </select>
          </template>
          <template v-else>
            <span>
              {{foodTypeList.find(t => t.id === business.orderTypeId)?.label || '未设置'}}
            </span>
          </template>
        </div>
        <div class="buttons">
          <button v-if="!editingBusiness" @click="editingBusiness = true">编辑店铺信息</button>
          <template v-else>
            <button @click="saveBusiness">保存</button>
            <button @click="cancelEditBusiness">取消</button>
          </template>
        </div>
      </div>
    </div>

    <!-- 食品管理 -->
    <div class="section">
      <h2>食品管理</h2>
      <div class="food-actions">
        <button @click="showAddFood = true">添加新食品</button>
      </div>

      <div class="food-list">
        <div v-for="food in foods" :key="food.id" class="food-item">
          <div class="food-info">
            <div class="food-text">
              <h3>{{ food.foodName }}</h3>
              <p>{{ food.foodExplain }}</p>
              <p class="price">¥{{ food.foodPrice }}</p>
              <p class="status" :class="{ 'on-sale': food.onSale, 'off-sale': !food.onSale }">
                {{ food.onSale ? '在售' : '下架' }}
              </p>
            </div>
            <img :src="food.foodImg" alt="食品图片" class="food-img" />
          </div>
          <div class="food-actions">
            <button @click="editFood(food)">编辑</button>
            <button @click="toggleFoodStatus(food)">
              {{ food.onSale ? '下架' : '上架' }}
            </button>
            <button @click="deleteFood(food.id)" class="delete-btn">删除</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑食品弹窗 -->
    <div v-if="showAddFood || editingFood" class="modal">
      <div class="modal-content">
        <h3>{{ editingFood ? '编辑食品' : '添加食品' }}</h3>
        <div class="form-item">
          <label>食品名称:</label>
          <input v-model="currentFood.foodName" />
        </div>
        <div class="form-item">
          <label>食品介绍:</label>
          <textarea v-model="currentFood.foodExplain"></textarea>
        </div>
        <div class="form-item">
          <label>价格:</label>
          <input v-model="currentFood.foodPrice" type="number" step="0.01" />
        </div>
        <div class="form-item">
          <label>图片URL:</label>
          <input v-model="currentFood.foodImg" placeholder="请输入图片网络地址" />
        </div>
        <div class="form-item">
          <label>
            <input v-model="currentFood.onSale" type="checkbox" />
            上架销售
          </label>
        </div>
        <div class="modal-buttons">
          <button @click="saveFood">保存</button>
          <button @click="cancelEditFood">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ProductManagement',
  data() {
    return {
      business: {},
      originalBusiness: {},
      editingBusiness: false,
      foods: [],
      showAddFood: false,
      editingFood: null,
      currentFood: {
        foodName: '',
        foodExplain: '',
        foodPrice: 0,
        foodImg: '',
        onSale: true
      },
      user: {},
      foodTypeList: [
        { id: 1, label: '中餐' },
        { id: 2, label: '快餐' },
        { id: 3, label: '韩餐' },
        { id: 4, label: '烧烤' },
        { id: 5, label: '饮品' },
        { id: 6, label: '火锅' },
        { id: 7, label: '川菜' },
        { id: 8, label: '湘菜' },
        { id: 9, label: '粤菜' },
        { id: 10, label: '东北菜' },
        { id: 11, label: '西餐' },
        { id: 12, label: '日料' },
        { id: 13, label: '轻食沙拉' },
        { id: 14, label: '素食' },
        { id: 15, label: '面包甜点' },
      ],
    };
  },
  created() {
    this.$axios.get(`/user`).then(res => {
      this.user = res.data;
      this.loadBusinessInfo();
      this.loadFoods();
    }).catch(err => {
      console.error('加载用户信息失败:', err);
      this.$message.error('加载用户信息失败');
    });
  },
  methods: {
    loadBusinessInfo() {
      const businessId = this.$route.query.businessId;
      if (businessId) {
        this.$axios.get(`/businesses/${businessId}`).then(res => {
          this.business = res.data.data;
          if (this.user && this.user.id) {
            this.business.userId = this.user.id;
          }
          this.originalBusiness = { ...this.business };
        }).catch(err => {
          this.$message.error('加载店铺信息失败');
        });
      }
    },

    loadFoods() {
      const businessId = this.$route.query.businessId;
      if (businessId) {
        this.$axios.get(`/foods?business=${businessId}`).then(res => {
          this.foods = res.data.data || [];
        }).catch(err => {
          console.error('加载食品列表失败:', err);
          this.$message.error('加载食品列表失败');
        });
      }
    },

    saveBusiness() {
      if (!this.business.orderTypeId) {
        this.$message.error('请先选择商铺分类');
        return;
      }
      this.$axios.patch(`/businesses/${this.business.id}`, this.business).then(res => {
        this.editingBusiness = false;
        this.originalBusiness = { ...this.business };
      }).catch(err => {
        console.error('更新店铺信息失败:', err);
        this.$message.error('更新店铺信息失败');
      });
    },

    cancelEditBusiness() {
      this.business = { ...this.originalBusiness };
      this.editingBusiness = false;
    },

    editFood(food) {
      this.editingFood = food;
      this.currentFood = { ...food };
    },

    saveFood() {
      if (this.editingFood) {
        // 更新食品
        this.$axios.put(`/foods/${this.editingFood.id}`, this.currentFood).then(res => {
          this.loadFoods();
          this.cancelEditFood();
        }).catch(err => {
          console.error('更新食品失败:', err);
          this.$message.error('更新食品失败');
        });
      } else {
        // 添加新食品
        const foodData = {
          ...this.currentFood,
          business: { id: this.business.id }
        };
        this.$axios.post('/foods', foodData).then(res => {
          this.loadFoods();
          this.cancelEditFood();
        }).catch(err => {
          console.error('添加食品失败:', err);
          this.$message.error('添加食品失败');
        });
      }
    },

    cancelEditFood() {
      this.showAddFood = false;
      this.editingFood = null;
      this.currentFood = {
        foodName: '',
        foodExplain: '',
        foodPrice: 0,
        foodImg: '',
        onSale: true
      };
    },

    toggleFoodStatus(food) {
      const updatedFood = { ...food, onSale: !food.onSale };
      this.$axios.patch(`/foods/${food.id}`, { onSale: updatedFood.onSale }).then(res => {
        this.loadFoods();
      }).catch(err => {
        console.error('更新食品状态失败:', err);
        this.$message.error('更新食品状态失败');
      });
    },

    deleteFood(foodId) {
      if (confirm('确定要删除这个食品吗？')) {
        this.$axios.delete(`/foods/${foodId}`).then(res => {
          this.loadFoods();
        }).catch(err => {
          console.error('删除食品失败:', err);
          this.$message.error('删除食品失败');
        });
      }
    },
    goBack() {
      this.$router.back();
    },
  }
}
</script>

<style scoped>
.wrapper {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.back-btn {
  position: absolute;
  left: 20px;
  top: 32px;
  font-size: 28px;
  cursor: pointer;
  color: #0097FF;
  z-index: 1001;
  background: #fff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0,0,0,.08);
}

.section h2 {
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #0097FF;
  padding-bottom: 10px;
}

.business-info .info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.business-info label {
  width: 120px;
  font-weight: bold;
  color: #555;
}

.business-info input,
.business-info textarea {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.business-info input:disabled,
.business-info textarea:disabled {
  background-color: #f5f5f5;
  color: #666;
}

.business-info textarea {
  min-height: 60px;
  resize: vertical;
}

.buttons {
  margin-top: 20px;
}

.buttons button {
  background: #0097FF;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
  font-size: 14px;
}

.buttons button:hover {
  background: #0077cc;
}

.food-actions {
  margin-bottom: 20px;
}

.food-actions button {
  background: #28a745;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.food-actions button:hover {
  background: #218838;
}

.food-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.food-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  background: #f9f9f9;
}

.food-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.food-info p {
  margin: 5px 0;
  color: #666;
}

.food-info .price {
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
}

.food-info .status {
  font-weight: bold;
}

.food-info .status.on-sale {
  color: #28a745;
}

.food-info .status.off-sale {
  color: #dc3545;
}

.food-item .food-actions {
  margin-top: 15px;
}

.food-item .food-actions button {
  background: #0097FF;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 5px;
  font-size: 12px;
}

.food-item .food-actions button:hover {
  background: #0077cc;
}

.food-item .food-actions .delete-btn {
  background: #dc3545;
}

.food-item .food-actions .delete-btn:hover {
  background: #c82333;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin-bottom: 20px;
  color: #333;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-item input,
.form-item textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-item textarea {
  min-height: 80px;
  resize: vertical;
}

.form-item input[type="checkbox"] {
  width: auto;
  margin-right: 8px;
}

.modal-buttons {
  margin-top: 20px;
  text-align: right;
}

.modal-buttons button {
  background: #0097FF;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
  font-size: 14px;
}

.modal-buttons button:hover {
  background: #0077cc;
}

.modal-buttons button:last-child {
  background: #6c757d;
}

.modal-buttons button:last-child:hover {
  background: #5a6268;
}

.food-text {
  flex: 1;
}

.food-info {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: space-between;
  min-height: 140px;
  /* 可根据实际内容调整高度 */
}

.food-img {
  width: 140px;
  height: 140px;
  object-fit: cover;
  margin-left: 30px;
  border-radius: 8px;
  background: #fff;
  display: block;
}
</style>